package com.example.demo.config;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2017</p>
 *
 * @author gaol
 * @version 1.0
 * @date 2017/6/5
 */
public class RedisCache implements Cache {

    private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);

    private final ReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    private final String id;

    private RedisTemplate redisTemplate;

    public RedisCache(String id) {
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {
        ValueOperations opsForValue = getRedisTemplate().opsForValue();
        opsForValue.set(key, value, 30, TimeUnit.MINUTES);
        logger.debug("Put query result to redis");

    }



    @Override
    public Object getObject(Object key) {
        ValueOperations opsForValue = getRedisTemplate().opsForValue();
        logger.debug("Get cached query result from redis");
        return opsForValue.get(key);
    }

    @Override
    public Object removeObject(Object key) {
        redisTemplate.delete(key);
        logger.debug("Remove cached query result from redis");
        return null;
    }

    @Override
    public void clear() {
        getRedisTemplate().execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
        logger.debug("Clear all the cached query result from redis");
    }

    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    private RedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = (RedisTemplate) ApplicationContextUtil.applicationContext.getBean("redisTemplate");
        }
        return redisTemplate;
    }
}
